import React from 'react';

import DBTable from 'components/DBTable';
import Logger from 'utils/Logger';
import ajax from 'utils/ajax';
import throttle from 'lodash/throttle';


import {
  Form,
  Input,
  Row,
  Col,
  Button,
  DatePicker,
  Select,
  Icon,
  Radio,
  InputNumber,
  Checkbox,
  message,
  Upload,
  notification
} from 'antd';

import loanManagerInnerTable from './loanManagerInnerTable';

const logger = Logger.getLogger('TreeDbTableView');
/**
 * 操作数据库中的一张表的组件, 又可以分为3个组件: 表单+表格+分页器
 */
class LoanDbTable extends DBTable {

  constructor(props) {
    super(props);
    console.log('this.state',this.state);
    this.tryFetchSchema(this.props);
  }


  componentWillReceiveProps = (nextProps) => {
      console.log(nextProps.tableType,'----------');
      if(nextProps.tableType){
        this.refreshNext(nextProps.tableType);
        this.tryFetchSchema(nextProps);
      }
  }

  createInnerTable () {
    return loanManagerInnerTable;
  }

  getInnerTable() {
      if (this.innerFromTable == null) {
        this.innerFromTable = Form.create()(this.createInnerTable());
      }
      const InnerFromTable = this.innerFromTable;
      return (<InnerFromTable requestParams={this.state.requestParams} data={this.state.data} tableLoading={this.state.tableLoading}
        schema={this.dataSchema} refresh={this.refresh} refreshTree={this.refreshTree}
        moduleName={this.state.moduleName}
        formSchema={this.formSchema}
        totalData={this.state.totalData}
        bottomInfo={this.state.bottomInfo}
        tableType={this.props.tableType}
        query={this.state.query}
        tableConfig={this.tableConfig} tableName={this.state.tableName} lookForm={this.lookForm} look={this.looks}/>);     
  }


  select(queryObj, page, pageSize, tableType) {
    const hide = message.loading('正在查询...', 0);
    const that = this;
    // console.log(this.state.tableName)
    var url = this.tableConfig.selectUrl ? `/${this.tableConfig.selectUrl}` : `/${this.state.tableName}/list`;
    let pageble = this.tableConfig.pageEnable;//是否分页参数 为0时不分页,其他时候都分页

    const promise = new Promise((resolve, reject) => {
      let param;
      if (pageble == 0) {
        param = { query: JSON.stringify(queryObj) };
      }
      else {
        param = { pageNum: page, numPerPage: pageSize, query: JSON.stringify(queryObj), type: tableType};
      }
      Object.assign(param, this.state.requestParams);
      Object.assign(param, this.props.params);
      ajax.post({
        url: url,
        params: param,
        success: function (result) {
          hide();
          result = that.handleResult(result);
          // console.log('result',result)
          resolve(result);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
             setTimeout(() => {
              hide();
              message.error(`查询失败,错误${XMLHttpRequest.status}...`);
            },500);
        },
      })
    })

    return promise;
  }


  /**
   * 切换分页时触发查询
   *
   * @param page
   */
  handlePageChange = (page) => {
    logger.debug('handlePageChange, page = %d', page);
    this.setState({ tableLoading: true });
    this.select(this.state.queryObj, page, this.state.pageSize, this.props.tableType).then((result) => {
      //message.success('查询成功');
      this.setState({
        currentPage: page,
        data: result.data.list,
        total: result.data.total,
        tableLoading: false,
      });
    }, this.handleError);
  }


  /**
   * 按当前的查询条件重新查询一次
   */
  refresh = () => {
    this.setState({ tableLoading: true });
    this.select(this.state.queryObj, this.state.currentPage, this.state.pageSize, this.props.tableType).then((result) => {
      
      // message.success('查询成功');
      /**
       * 查询动画结束有一定时间，延时500ms显示成功，让节奏舒适一点
       */
      setTimeout(function () {
        message.success('查询成功');
      }, 500);
      this.onBeforeRefresh(result);

      let pageble = this.tableConfig.pageEnable;
      if (pageble == 0) {
        this.setState({ pageSize: result.data.total });
      }
      this.setState({
        data: result.data.list,
        totalData: result.data,
        total: result.data.total,
        tableLoading: false,
      });
    }, this.handleError);
  }

  refreshNext = (tableType) => {
      this.setState({ tableLoading: true });
      this.select(this.state.queryObj, this.state.currentPage, this.state.pageSize, tableType).then((result) => {
      
      // message.success('查询成功');
      /**
       * 查询动画结束有一定时间，延时500ms显示成功，让节奏舒适一点
       */
      setTimeout(function () {
        message.success('查询成功');
      }, 500);
      this.onBeforeRefresh(result);

      let pageble = this.tableConfig.pageEnable;
      if (pageble == 0) {
        this.setState({ pageSize: result.data.total });
      }
      this.setState({
        data: result.data.list,
        totalData: result.data,
        total: result.data.total,
        tableLoading: false,
      });
    }, this.handleError);
  }


  /**
   * 点击提交按钮时触发查询
   *
   * @param queryObj
   */
  handleFormSubmit = (queryObj) => {
    logger.debug('handleFormSubmit, queryObj = %o', queryObj);
    this.setState({ tableLoading: true });
    // 这时查询条件已经变了, 要从第一页开始查
    this.select(queryObj, 1, this.state.pageSize, this.props.tableType).then((result) => {
      //message.success('查询成功');
      this.onBeforeRefresh(result);
      this.setState({
        currentPage: 1,
        data: result.data.list,
        total: result.data.total,
        tableLoading: false,
        queryObj: queryObj,
      });
    }, this.handleError);
  }
  
    /**
   * 尝试获取某个表的querySchema和dataSchema
   * 无论是从远端获取还是从本地配置读取, 这个方法必须是同步的
   *
   * @param dbName
   * @param tableName
   */
  tryFetchSchema(props) {
    var routes;
    const tableType = props.tableType;

    if (props.routes == undefined) {
      routes = props;
    }
    else {
      routes = props.routes.pop();
    }

    // 这个tableName是路由表配置中传过来的
    // 可以用这个方法向组件传值
    const tableName = routes.tableName.toLowerCase();
    {
      if (routes.tableName) {
        this.state.moduleName = routes.tableName;
      }
      if (routes.queryName) {
        this.state.queryName = routes.queryName;
      }
    }
    if (tableName) {
      logger.info('init component DBTable with tableName = %s', tableName);
    } else {
      logger.error('can not find tableName, check your router config');
      this.inited = false;  // 是否成功获取schema
      this.errorMsg = '找不到表名, 请检查路由配置';  // 如果没能成功获取schema, 错误信息是什么?
      return;
    }

    // 其实很多这种this.xxx变量也可以做成状态, 看情况了
    // 关键是这些变量变化时, 是否要触发重新render?

    this.state.tableName = tableName;
    const { queryName } = this.state;

    try{
     this.lookForm = require(`schema/${tableName}/lookSchema.js`) 
    }catch(e){
      logger.error(`${tableName},${queryName}`, e);
      this.inited = false;
      this.errorMsg = `加载${tableName}表的lookSchema出错, 请检查配置`;
      return;
    }
    // 尝试加载querySchema
    try {
      this.querySchema = require(`schema/${tableName}/${queryName}.js`)
    } catch (e) {
      logger.error(`${tableName},${queryName}`, e);
      this.inited = false;
      this.errorMsg = `加载${tableName}表的${queryName}出错, 请检查配置`;
      return;
    }
    // 尝试加载formSchema
    try {
      this.formSchema = require(`schema/${tableName}/formSchema/formSchema.${tableType}.js`);
    } catch (e) {
      logger.error('load query schema error: %o', e);
      this.inited = false;
      this.errorMsg = `加载${tableName}表的formSchema出错, 请检查配置`;
      return;
    }

    // 尝试加载dataSchema
    try {
      this.dataSchema = require(`schema/${tableName}/dataSchema/dataSchema.${tableType}.js`);
    } catch (e) {
      logger.error('load data schema error: %o', e);
      this.inited = false;
      this.errorMsg = `加载${tableName}表的dataSchema出错, 请检查配置`;
      return;
    }

    // 尝试加载个性化配置, 加载失败也没影响
    try {
      var tableConfig = require(`schema/${tableName}/config/config.${tableType}.js`);
      Object.assign(this.tableConfig, tableConfig);
    } catch (e) {
      logger.warn('can not find config for table %s, use default instead', tableName);
    }

    this.inited = true;
  }


  // render() {
  //   // 如果没能成功加载schema, 显示错误信息
  //   if (!this.inited) {
  //     return (
  //       <Error errorMsg={this.errorMsg} />
  //     );
  //   }

  //   return (
  //     <div>
  //       {this.getInnerForm()}
  //       {this.getInnerTable()}
  //       {!!this.state.total && <InnerPagination currentPage={this.state.currentPage} total={this.state.total} pageSize={this.state.pageSize}
  //         parentHandlePageChange={this.handlePageChange} tableConfig={this.tableConfig}
  //         tableName={this.state.tableName} />}
  //     </div>
  //   );
  // }

}

export default LoanDbTable;
